<template>
  <div>
    <el-tabs v-model="activeName">
        <el-tab-pane label="基础信息" name="Datas">
            <el-form :model="model" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm page-form">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="单号" prop="Number">
                    <el-input v-model="model.Number" placeholder="请输入采购退货单号"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="供应商" prop="VendorId">
                    <el-select :value="model.VendorName" placeholder="请选择供应商名称" @change="VendorChange">
                      <el-option v-for="Vendor in VendorList" :key="Vendor.Id" :label="Vendor.VendorName" :value="Vendor"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="入库仓" prop="WarehouseId">
                    <el-select :value="model.WarehouseName" placeholder="请选择入库仓" @change="WarehouseChange">
                      <el-option v-for="Warehouse in WarehouseList" :key="Warehouse.Id" :label="Warehouse.WarehouseName" :value="Warehouse"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label="付款账户" prop="PaymentAccount">
                     <el-input v-model="model.PaymentAccount" placeholder="请输入付款账户"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="付款方式" prop="PaymentCategory">
                    <el-select v-model="model.PaymentCategory">
                      <el-option label="现金交易" value="现金交易"></el-option>
                      <el-option label="银行支付" value="银行支付"></el-option>
                      <el-option label="微信支付" value="微信支付"></el-option>
                      <el-option label="支付宝支付" value="支付宝支付"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="收款日期" prop="PaymentTime">
                    <el-date-picker v-model="model.PaymentTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label="退货日期" prop="ReturnDate">
                    <el-date-picker v-model="model.ReturnDate" type="datetime" placeholder="选择日期时间"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="出库日期" prop="DeliveryDate">
                    <el-date-picker v-model="model.DeliveryDate" type="datetime" placeholder="选择日期时间"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="单据状态" prop="Status">
                    <el-select v-model="model.Status" >
                      <el-option label="待审核" value="0"></el-option>
                      <el-option label="已审核" value="1"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label="联系人" prop="VendorContact">
                    <el-input v-model="model.VendorContact" placeholder="请输入联系人"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="联系人电话" prop="VendorContactTel">
                    <el-input v-model="model.VendorContactTel" placeholder="请输入联系人电话"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="备注" prop="Remark">
                    <el-input v-model="model.Remark"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

            </el-form>
        </el-tab-pane>

        <el-tab-pane label="添加订单" name="Addanorder">
          <div class="page-tool">
            <el-button type="primary" plain icon="el-icon-plus" @click="addMachine" size="small">选择单据</el-button>
            <el-button type="danger" plain icon="el-icon-delete" size="small" @click="delBom">删除</el-button>
          </div>

          <el-table :data="tableData" ref="dataForm" v-loading="isLoading" height="300" show-summary :summary-method="getSummaries">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="ItemCode" label="编号" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="ItemName" label="名称" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="Spec" label="规格" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="CurrCount" label="当前库存" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="UnitOfMeasure" label="单位" :show-overflow-tooltip="true"></el-table-column>

            <el-table-column prop="Count" label="数量" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-input v-model="scope.row.Count" @change="handleTaxChange(scope.row)"/>
              </template>
            </el-table-column>
            
            <el-table-column prop="Price" label="商品单价" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-input v-model="scope.row.Price" @change="handleTaxChange(scope.row)"></el-input>
              </template>
            </el-table-column>
            
            <!--
              <el-table-column prop="Amount" label="金额" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-input v-model="scope.row.Price" @change="handleTaxChange(scope.row)"></el-input>
              </template>
            </el-table-column>
            -->

            <el-table-column prop="Amount" label="金额" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column label="操作" :show-overflow-tooltip="true">
              <template slot-scope="scope">
               <el-button type="text" @click="del(scope.row)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
    </el-tabs>

    <div class="page-form-action">
      <el-button type="primary" @click="submitForm">{{ isUpdate ? '立即保存' : '立即创建' }}</el-button>
      <el-button @click="resetForm">重置</el-button>
    </div>

    <!--弹框-->
    <el-dialog append-to-body  :close-on-click-modal="false" :title="dialogDomain.title" :visible.sync="dialogDomain.dialogVisible" width="70%">
      <OrderPoReturnItem @callback="AddBomCallBack" :BomList="WhPoInboundList"  v-if="dialogDomain.dialogVisible"/>
    </el-dialog>
  </div>
</template>

<script>
import OrderPoReturnItem from './OrderPoReturnItem.vue'
export default {
  components:{
    OrderPoReturnItem
  },
  props:{
    model: {
      require: true,
      type: Object
    },
    isUpdate: {
      require: true,
      type: Boolean
    },
    WarehouseList:{
      type: Array,
      required: true
    },
    VendorList:{
      type: Array,
      required: true
    },
  },
  data(){
    var validatePhone = ( rule,value, callback) => {
            var emalRule= /^\d{11}$/;
            if (!value) {
            return callback(new Error('请输入联系电话'));
            } else if (!emalRule.test(value)) {
            callback(new Error('请输入正确联系电话'));
            } else {
            callback();
            }
        };
    return{
      activeName:'Datas',
      tableData:[],
      //采购入库数据
      WhPoInboundList:[],
      isLoading:false,
      rules:{
        Number: { required: true, message: '请输入采购退货单号', trigger: 'blur' },
        VendorId: { required: true, message: '请选择供应商名称', trigger: 'blur' },
        WarehouseId: { required: true, message: '请选择入货仓', trigger: 'blur' },
        PaymentAccount: { required: true, message: '请输入付款账户', trigger: 'blur' },
        PaymentCategory: { required: true, message: '请选择付款方式', trigger: 'blur' },
        PaymentTime: { required: true, message: '请选择收款日期', trigger: 'blur' },
        ReturnDate: { required: true, message: '请选择退货日期', trigger: 'blur' },
        DeliveryDate: { required: true, message: '请选择出库日期', trigger: 'blur' },
        Status: { required: true, message: '请选择采购退货状态', trigger: 'blur' },
        VendorContact: { required: true, message: '请输入联系人', trigger: 'blur' },
        VendorContact: { required: true, message: '请输入联系人', trigger: 'blur' },
        VendorContactTel:  { validator: validatePhone, trigger: 'blur' },
      },
      dialogDomain:{
        title:'选择采购入库单据',
        dialogVisible:false,
      }
    }
  },
  created(){
    if(this.isUpdate){
      this.GetOrderPoReturnId()
    }
  },
  methods:{
    //运算
    getSummaries(param){
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
            sums[index] = '总价';
            return;
        }
        if (column.property === 'Amount' || column.property === 'Price') {
          const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    if (!isNaN(value)) {
                        return prev + curr;
                        
                    } else {
                        return prev;
                    }
                }, 0);
                sums[index] += ' 元';
            } else {
                sums[index] = '';
            }
        }
        else {
            sums[index] = '';
        }
          
      });
      return sums;
    },
    //金额
    handleTaxChange(){
      row.Amount = row.Count * row.Price;//金额
    },
    //供应商
    VendorChange(model){
      this.model.VendorId=model.Id;
      this.model.VendorName=model.VendorName;
      console.log(model);
    },
    //仓库
    WarehouseChange(model){
      this.model.WarehouseId = model.Id;
      this.model.WarehouseName=model.WarehouseName;
      console.log(model)
    },
    addMachine(){
      this.dialogDomain.title="选择单据";
      this.dialogDomain.dialogVisible=true;
    },
    delBom(){
      if(this.$refs.dataForm.selection.length<=0){
        this.showNotify('请选择一项');
        return;
      }
      this.$refs.dataForm.selection.forEach(row => {
        const index = this.tableData.indexOf(row);
        this.tableData.splice(index, 1);
      });
    },
    del(model) {
      let index = this.tableData.indexOf(model);
      this.tableData.splice(index,1);
    },
    submitForm(){
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if(this.tableData && this.tableData.length > 0){
             if (this.isUpdate) {
              this.put();
            }
            else {
              this.add();
            }
          }else{
            this.showNotify('请选择单据');
            return false;
          }
        } else {
          this.showNotify('请输入必填项');
          return false;
        }
      });
    },
    add(){
      console.log(this.model)
      this.$http.postForm('/api/OrderPoReturn', { model: this.model,OrderPoReturnItemString:JSON.stringify(this.tableData) }, { loading: this.$loading() })
      .then(res => {
        this.$emit('callback');
      })
    },
    put(){
      console.log(this.tableData);
      this.$http.putForm('/api/OrderPoReturn', { model: this.model,OrderPoReturnItemString:JSON.stringify(this.tableData) }, { loading: this.$loading() })
      .then((res) => {
          this.$emit('callback');
      })
    },
    //重置
    resetForm() {
      if(this.isUpdate){
      }else{
        this.$refs['ruleForm'].resetFields();
        this.tableData = [];
      }
    },
    handleTaxChange(){
      row.Amount = row.Count * row.Price;//金额
    },
    
    GetOrderPoReturnId(){
      this.isLoading=true;
      this.$http.get('/api/OrderPoReturn/GetOrderPoReturnId',{
        params:{
          Id:this.model.Id,
          WarehouseId:this.model.WarehouseId
        }
      })
      .then(res => {
        this.isLoading=false;
        this.tableData = res.Data;
      })
    },

    AddBomCallBack(model){
      console.log(model);
      this.dialogDomain.dialogVisible = false;

      this.model.WhPoInboundId=model.Id
      //console.log(this.model.WhPoInboundId);


      this.$http.get('/api/WhPoInbound/GetWhPoInboundItemById',{
        params:{
          WhPoInboundId:model.Id,
          WarehouseId:model.WarehouseId
        }
      })
      .then(res => {
        this.tableData = res.Data;
      })
      this.model.Number = model.Number;
      this.model.VendorName = model.VendorName;
      this.model.VendorContact = model.VendorContact;
      this.model.VendorContactTel = model.VendorContactTel;
      this.model.PaymentCategory = model.PaymentCategory;
      this.model.PaymentAccount = model.PaymentAccount;
      this.model.PaymentTime = model.PaymentTime;
      this.model.WarehouseId = model.WarehouseId;
      this.model.WarehouseName = model.WarehouseName;
      this.model.DeliveryDate = model.DeliveryDate;
      this.model.Remark = model.Remark;
    }
  }
}
</script>

<style>

</style>